package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbit.main.constant.DevicePriorityConstant;
import com.tbit.main.dao.core.DevicePriorityDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountConfig;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.DevicePriority;
import com.tbit.main.pojo.DispatchConfig;
import com.tbit.main.service.*;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Author: chen
 * @Description: 功能优先级
 * @Date: 创建于 11:27 2023/3/2
 */
@Service
public class DevicePriorityServiceImpl extends ServiceImpl<DevicePriorityDao, DevicePriority> implements
        DevicePriorityService {

    @Autowired
    private MachineAbnormalService machineAbnormalService;
    @Autowired
    private MachineBorrowService machineBorrowService;
    @Autowired
    private MachineOccupyService machineOccupyService;
    @Autowired
    private MachineFaultService machineFaultService;
    @Autowired
    private DataService dataService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private MachineNoIncomeService machineNoIncomeService;
    @Autowired
    private StockMachineService stockMachineService;
    @Autowired
    private DetentionMachineBoundService detentionMachineBoundService;

    @Override
    public void add(List<DevicePriority> list, AccountUser accountUser, Integer accountId) {
        Date date = new Date();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("accountId", accountId);
        /**每次传递过来的数量必须大于等于15数量*/
        if (list.size() < 15) {
            throw new BaseException("DevicePriority.is.less");
        }
        /**先删除，后添加*/
        QueryWrapper delWrapper = new QueryWrapper();
        delWrapper.eq("accountId", accountId);
        remove(delWrapper);

        list.forEach(devicePriority -> {
            devicePriority.setAccountId(accountId);
            devicePriority.setAddTime(date);
            devicePriority.setUserId(accountUser.getAccountUserId());
        });
        saveBatch(list);
    }

    @Override
    public List<DevicePriority> getByAccountId(AccountUser accountUser, Integer accountId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("accountId", accountId);
        List<DevicePriority> devicePriorities = list(queryWrapper);
        if (devicePriorities.isEmpty()) {
            /**初始化一个*/
            devicePriorities = DevicePriorityConstant.getDefaultDevicePriority();
            add(devicePriorities, accountUser, accountId);
        }
        return devicePriorities;
    }

    @Override
    public List<Integer> checkPriority(List<Integer> machineIds, Integer accountId, Integer level) {
        if (CollUtil.isEmpty(machineIds)) {
            return new LinkedList<>();
        }

        LogUtil.info("车辆优先级，车辆id==" + machineIds);

        /**查询等级*/
        QueryWrapper levelWrapper = new QueryWrapper();
        levelWrapper.eq("accountId", accountId);
        levelWrapper.eq("functionId", level);
        DevicePriority devicePriority = getOne(levelWrapper);
        List<Integer> list = new ArrayList<>();
        if (devicePriority != null) {
            LogUtil.info("当前优先级:" + devicePriority.toString());
            /**查询优先*/
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("accountId", accountId);
            queryWrapper.lt("level", devicePriority.getLevel());
            queryWrapper.orderByAsc("functionId");
            List<DevicePriority> devicePriorities = list(queryWrapper);

            /**查询需要去除的车辆id*/
            if (!devicePriorities.isEmpty()) {
                LogUtil.info("更高优先级:" + devicePriorities.toString());

                List<Integer> lastType = devicePriorities.stream().map(DevicePriority::getFunctionId).collect(Collectors.toList());

                List<Integer> lastTypeList = devicePriorities.stream().map(DevicePriority::getFunctionId).collect(Collectors.toList());
                List<Integer> abnormalType = DevicePriorityConstant.getAbnormal(lastTypeList);
                LogUtil.info("异常类型:" + abnormalType.toString());
                /**查询异常车辆*/
                if (!abnormalType.isEmpty()) {
                    List<Integer> abnormalMachine = machineAbnormalService.getByMachineIdsIdAndType(machineIds, abnormalType);
                    list = abnormalMachine;
                    LogUtil.info("查询异常车辆:" + list.toString());
                }

                /**骑行中车辆*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_QXZ)) {
                    List<Integer> exsitIds = machineBorrowService.getExist(machineIds);
                    LogUtil.info("骑行中车辆:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**运维占用*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_YWZY)) {
                    List<Integer> exsitIds = machineOccupyService.getExist(machineIds);
                    LogUtil.info("运维占用:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**运维故障*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_YWGZ)) {
                    List<Integer> exsitIds = machineFaultService.getExist(machineIds, 0);
                    LogUtil.info("运维故障:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**低电*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_DD)) {
                    AccountConfig accountConfig = dataService.getAccountConfig(accountId);
                    if (accountConfig != null) {
                        List<Integer> exsitIds = machineStatusService.getExist(machineIds, accountConfig.getSocLimit());
                        LogUtil.info("低电:" + exsitIds.toString());
                        list.addAll(exsitIds);
                    }
                }

                /**闲置车辆*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_XZCL)) {
                    DispatchConfig dispatchConfig = dataService.getDispatch(accountId);
                    if (dispatchConfig != null && dispatchConfig.getDispatchLeave() > 0) {
                        List<Integer> exsitIds = machineService.getExist(machineIds, DateTimeUtil.getHoursAgo(dispatchConfig.getDispatchLeave()));
                        LogUtil.info("闲置车辆:" + exsitIds.toString());
                        list.addAll(exsitIds);
                    }
                }

                /**用户故障*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_YHGZ)) {
                    List<Integer> exsitIds = machineFaultService.getExist(machineIds, 1);
                    LogUtil.info("用户故障:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**无盈利*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_WYL)) {
                    List<Integer> exsitIds = machineNoIncomeService.getExist(machineIds);
                    LogUtil.info("无盈利:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**扣押状态*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_KYZT)) {
                    List<Integer> exsitIds = detentionMachineBoundService.getExist(machineIds);
                    LogUtil.info("扣押状态:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
                /**入库中*/
                if (lastType.contains(DevicePriorityConstant.DEVICEPRIORITY_RKZ)) {
                    List<Integer> exsitIds = stockMachineService.getExist(machineIds);
                    LogUtil.info("入库中:" + exsitIds.toString());
                    list.addAll(exsitIds);
                }
            }
        }

        list = getExit(machineIds, list);
        if (list != null && !list.isEmpty()) {
            LogUtil.info("筛选车辆取交集：" + list.toString());
        }
        return list;
    }

    /**
     * 求交集
     *
     * @param list
     * @param ids
     * @return
     */
    public List<Integer> getExit(List<Integer> list, List<Integer> ids) {
      /*  list.addAll(ids);
        List<Integer> listAllDistinct = list.stream().distinct().collect(toList());
        return listAllDistinct;*/
        List<Integer> intersection = list.stream().filter(item -> ids.contains(item)).collect(toList());
        return intersection;
    }
}
